<template>
  <!--商品添加基本信息  -->
  <div id="baseShop">
    <w-panel-wrap>
      <w-panel-title :title="'基本信息'"></w-panel-title>
      <w-panel>
        <w-form-validate @on-validate="onValidate">
          <div class="item">
            <div class="item-group">
              <span class="label box">商品分类:</span>
              <div class="box" v-if="!$store.state.className">
                <div class="item-c" v-text="'请选择分类'">
                </div>
                <div class="tip">
                  <button class="btn main" type="button" @click="editDone()">编辑</button>
                </div>
              </div>
              <div class="box" v-if="$store.state.className">
                <div class="item-c">{{$store.state.className || ''}}</div>
                <div class="tip">
                  <button class="btn main" type="button" @click="editDone()">编辑</button>
                </div>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">拼单结束时间:</span>
              <div class="box">
                <w-datepicker v-model="submitData.fightGoodsEndTime" :split="true"></w-datepicker>
                <div class="tip">
                  <span class="label-c">结束前可修改时间</span>
                </div>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">商品名称:</span>
              <div class="box box-w large-input">
                <w-input v-model="submitData.goodsName" tip="商品标题名称长度最少3个字符，最长50个字符" :validate="true" :maxLength="50" rule="isEmpty|between:3-50" error="商品名称不能为空|最少3个字符，最长50个字符">
                </w-input>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">品牌:</span>
              <div class="box">
                <div style="width:208px;display:inline-block;">
                  <w-select v-model="submitData.goodsBrandId" :options="brandList"></w-select>
                </div>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">商品价格:</span>
              <div class="box">
                <div class="goods-price" v-for="(price,index) in prices" :key="index">
                  <w-input v-model="price.minCount" :validate="true" rule="isEmpty" error="必填">
                  </w-input>&nbsp;-&nbsp;
                  <w-input v-model="price.maxCount" :validate="true" rule="isEmpty" error="必填" id="valdSel"></w-input>&nbsp;件&nbsp;
                  <w-input v-model="price.money" :validate="true" rule="isEmpty" error="必填"></w-input>&nbsp;元&nbsp;
                  <span class="label-c" v-if="index == 0">例如:10-20件，10元(最多可添加三个阶梯价格)</span>
                  <span class="label-b" v-if="index == prices.length - 1 && index != 0" @click="doDeletePrice(index)">删除</span>
                </div>
                <div class="tip">
                  <button class="btn main" @click="addPrice" v-if="prices.length < 3">增加</button>
                </div>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">商品货号:</span>
              <div class="box box-w large-input">
                <w-input v-model="submitData.goodsSerial" :minLength="6" rule="isEmpty|between:6-50" :validate="true" error="编号必填|最少六位编号" tip="商品货号是指商家管理的商品编号，最少六位编号，买家不可见" v-if="!goodsNumber || goodsNumber == ''"></w-input>
                <input v-model="goodsNumber" readonly class="good-number" v-if="goodsNumber && goodsNumber != ''"></input>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box ">商品类型:</span>
              <div class="box">
                <w-radio name="goodsNumType" :label="'0'" v-model.number="submitData.goodsNumType">期货</w-radio>
                <w-radio name="goodsNumType" :label="'1'" v-model.number="submitData.goodsNumType">现货</w-radio>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">商品重量:</span>
              <div class="box">
                <w-input v-model.number="submitData.goodsWeight" :validate="false"></w-input>
                <div class="tip">
                  <span class="label-c">单位：KG</span>
                </div>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="item-group">
              <span class="label box label-h">运费模板：</span>
              <div class="box">
                <div style="width:208px;display:inline-block;">
                  <w-select v-model="submitData.transportId" :options="transportList"></w-select>
                </div>
              </div>
            </div>
          </div>
          <div class="item" style="border:0;">
            <div class="item-group">
              <span class="label box label-h"></span>
              <div class="box">
                <button class="btn main" type="button" @click="onPrev">上一步</button>
                <button class="btn main">下一步</button>
              </div>
            </div>
          </div>
        </w-form-validate>
      </w-panel>
    </w-panel-wrap>
  </div>
</template>
<script>
import { apiGoods } from '../../../common/api'
import { formatDate } from '../../../common/util'
import app from '../../../main'
export default {
  data() {
    return {
      tierdPrice: [],
      brandList: [],
      transportList: [],
      goodsNumber: '',
      submitData: {
        goodsStoreId: this.$store.getters.storeId,
        transportId: '',
        gcId: '' || parseInt(this.$route.params.id),
        fightGoodsEndTime: '',
        goodsName: '',
        goodsBrandId: '',
        goodsSerial: '',
        goodsNumType: 0,
        goodsWeight: '',
        tierdPrice: []
      },
      prices: [
        {minCount: '', maxCount: '', money: ''}
      ]
    }
  },
  created() {
    this.queryGoodsBrand()
    // 查询运费模板
    this.queryGoodsTranSport()
    // 查询商品详情
    if (this.$route.params.gdId) {
      this.$store.commit('updateGoodsId', this.$route.params.gdId)
      this.getGoodsDetail()
    } else {
      // 如果是新增进入该页面则关闭进入页面
      this.$store.commit('intoThisPage', 0)
    }
  },
  methods: {
    // 提交商品基本信息
    goodsInsert() {
      let _this = this
      let flag = true
      if (_this.prices.length > 1) {
        // 判断阶梯价格
        for (let i = 0; i < _this.prices.length; i++) {
          if (_this.prices[i].minCount * 1 >= _this.prices[i].maxCount * 1) {
            app.$toast('最小值必需小于最大值')
            $('#valdSel .form-control').focus()
            flag = false
            return
          }
          if (i > 0 && _this.prices[i - 1].maxCount * 1 >= _this.prices[i].minCount * 1 || i > 0 && _this.prices[i - 1].maxCount * 1 - _this.prices[i].minCount * 1 != -1) {
            app.$toast('输入件数的第一个最小值必需大于前一个的最大值且只能大于一')
            flag = false
            return
          }
        }
        if (flag) {
           for (let i = 0; i < _this.prices.length; i++) {
            // 组合阶梯价格
            _this.submitData.tierdPrice.push({
              count: `${_this.prices[i].minCount}-${_this.prices[i].maxCount}`,
              price: _this.prices[i].money
            })
          }
        }
      } else {
        this.prices.forEach((o) => {
          if (o.minCount * 1 >= o.maxCount * 1) {
            app.$toast('最小值必需小于最大值')
          } else {
            // 组合阶梯价格
            this.submitData.tierdPrice.push({
              count: `${o.minCount}-${o.maxCount}`,
              price: o.money
            })
          }
        })
      }
      if (this.submitData.tierdPrice.length > 0) {
        if (this.$route.params.gdId || this.$store.getters.intoNextPage == 3) {
            this.submitData.goodsId = this.$route.params.gdId
          if (this.$store.getters.intoNextPage == 3 && !this.$route.params.gdId) {
            this.submitData.goodsId = this.$store.getters.goodsId
          }
          this.submitData.accessToken = this.$store.getters.token
          apiGoods.submitTextContent(this.submitData).then((resp) => {
            app.$toast('编辑成功')
            this.submitData.tierdPrice = []
            if (typeof (this.$route.params.gdId) == 'undefined') {
              this.$store.commit('intoThisPage', 1)
            }
            // 页面跳转（进入下一页）
            setTimeout(() => {
              let index = this.$parent.$parent.curIndex
              this.$parent.$parent.onChangeContent(index + 1)
              if (typeof (this.$route.params.gdId) == 'undefined') {
                this.$store.commit('intoThisPage', 0)
              }
            }, 2000)
          })
        } else {
          apiGoods.goodsInsertFirst(this.submitData).then((resp) => {
            // 商品id
            this.$store.dispatch('updateGoodsId', resp.goodsId)
            this.$toast('新增成功')
            this.goodsNumber = this.submitData.goodsSerial
            this.submitData.tierdPrice = []
            if (typeof (this.$route.params.gdId) == 'undefined') {
              this.$store.commit('intoThisPage', 1)
            }
            // 页面跳转（进入下一页）
            setTimeout(() => {
              let index = this.$parent.$parent.curIndex
              this.$parent.$parent.onChangeContent(index + 1)
              if (typeof (this.$route.params.gdId) == 'undefined') {
                this.$store.commit('intoThisPage', 0)
              }
            }, 2000)
          })
        }
      }
    },
    // 查询品牌
    queryGoodsBrand() {
      apiGoods.queryGoodsBrand().then((resp) => {
        resp.goodsBrandList.forEach((o) => {
          this.brandList.push({
            value: o.goodsBrandId,
            label: o.goodsBrandName
          })
        })
      })
    },
    // 运费模板
    queryGoodsTranSport() {
      let json = {
        storeId: this.submitData.goodsStoreId
      }
      apiGoods.queryGoodsTranSport(json).then((resp) => {
        resp.transportList.forEach((o) => {
          this.transportList.push({
            value: o.transportId,
            label: o.transportName
          })
        })
      })
    },
    // 新增商品价格
    addPrice() {
      this.prices.push({ minCount: '', maxCount: '', money: '' })
    },
    // 提交
    onValidate() {
      let date = new Date()
      if (this.submitData.fightGoodsEndTime == '') {
        $toast('请选择拼单时间')
        return
      }
      if (!this.submitData.gcId) {
        $toast('请选择分类')
        return
      }
      let newDate = new Date(this.submitData.fightGoodsEndTime)
      if (date - newDate >= 0) {
        $toast('拼单时间结束时间必须大于当前时间')
        return
      }
      if (this.submitData.goodsName == '') {
        $toast('请输入商品名称')
        return
      }
      // if (this.submitData.goodsBrandId == '') {
      //   $toast('请选择品牌')
      //   return
      // }
      if (this.prices.length <= 0) {
        $toast('请输入价格')
        return
      }
      if (this.submitData.transportId == '') {
        $toast('请选择运费模板')
        return
      }
      sessionStorage.setItem('goodsNumType', this.submitData.goodsNumType)
      this.goodsInsert()
    },
    // 上一步
    onPrev() {
      // 激活进入页面
      this.$store.commit('intoThisPage', 1)
      let index = this.$parent.$parent.curIndex
      if (index == 0) {
        this.$router.go(-1)
      } else {
        this.$parent.$parent.onChangeContent(index - 1)
      }
    },
    editDone() {
      this.$router.push(`/goods/classify/${this.$route.params.id}/${this.$route.params.gdId}`)
    },
    // 根据商品ＩＤ查询商品数据
    getGoodsDetail() {
        apiGoods.goodsInsertSeconds(this.$route.params.gdId).then((resp) => {
          this.$store.dispatch('goodsDetails', resp.goods.goodsDetails)
        if (resp.goods) {
            this.submitData.goodsNumType = resp.goods.goodsNumType
            sessionStorage.setItem('goodsNumType', this.submitData.goodsNumType)
          if (resp.goods.id) {
            this.$store.dispatch('updateGoodsId', resp.goods.id)
          }
          if (resp.goods.classNameThree) {
            this.$store.state.className = resp.goods.classNameOne + '>' + resp.goods.classNameTwo + '>' + resp.goods.classNameThree
          } else if (this.$route.params.key == 11) {
            this.$store.state.className = this.$store.state.className
          } else {
            this.$store.state.className = ''
          }
          if (resp.goods.transportId) {
            this.submitData.transportId = resp.goods.transportId
            this.$store.state.transportId = resp.goods.transportId
          }
          if (resp.goods.fightGoodsEndTime) {
            this.submitData.fightGoodsEndTime = resp.goods.fightGoodsEndTime.substring(0, 10)
          }
          if (resp.goods.goodsBrandId) {
            this.submitData.goodsBrandId = resp.goods.goodsBrandId
          }
          if (resp.goods.crowdfundingCount) {
            sessionStorage.setItem('crowdfundingCount', resp.goods.crowdfundingCount)
          }
          if (resp.goods.goodsSerial) {
            this.submitData.goodsSerial = resp.goods.goodsSerial
            this.goodsNumber = this.submitData.goodsSerial
          }
          if (resp.goods.goodsWeight) {
            this.submitData.goodsWeight = resp.goods.goodsWeight
          }
          if (resp.goods.goodsName) {
            this.submitData.goodsName = resp.goods.goodsName
          }
          if (resp.goods.goodsMainPhotoPath) {
            this.$store.dispatch('photoMain', resp.goods.goodsMainPhotoPath)
          }
          if (resp.goods.photoUrlPrefix) {
            this.$store.dispatch('photoMainUrl', resp.goods.photoUrlPrefix)
          }
          if (resp.goods.goodsInfoPhotePath) {
            this.$store.dispatch('photoInfo', resp.goods.goodsInfoPhotePath)
          }
          if (resp.goods.photoUrlPrefix) {
            this.$store.dispatch('photoInfoUrl', resp.goods.photoUrlPrefix)
          }
          if (resp.goods.goodsDetails) {
            this.$store.dispatch('goodsDetails', resp.goods.goodsDetails)
          }
          if (resp.goods.goodsProperty) {
            this.$store.commit('feature', resp.goods.goodsProperty)
          }
          if (resp.goods.goodsInventoryDetail) {
            this.$store.commit('goodsInventoryDetail', resp.goods.goodsInventoryDetail)
            this.$store.commit('goodsDetailsList', JSON.parse(resp.goods.goodsInventoryDetail))
          }
          if (resp.goods.tierdPrice) {
            let tierdPrice = JSON.parse(resp.goods.tierdPrice)
            tierdPrice.forEach((v, index) => {
              let minCount = v.count.split('-')[0]
              let maxCount = v.count.split('-')[1]
              this.$set(this.prices, index, { minCount: minCount, maxCount: maxCount, money: v.price })
            })
          }
          if (resp.goods.goodsGspPhotoDetail) {
            this.$store.commit('photoGspUrl', resp.goods.photoUrlPrefix)
            let goodsDetailsList = JSON.parse(resp.goods.goodsGspPhotoDetail)
            goodsDetailsList.forEach((v) => {
              v.specpropertyPhotoPath = resp.goods.photoUrlPrefix
            })
            this.$store.commit('goodsDetailsList', goodsDetailsList)
          }
        }
      })
    },
    // 删除阶梯价格
    doDeletePrice(id) {
      this.prices = this.prices.slice(0, id)
    }
  }
}
</script>
<style lang="scss">
#baseShop {
  .select-drop {
    position: inherit!important;
    max-height: 100px;
  }
  .error-tip {
    position: absolute;
    left: 20px;
    z-index: 2
  }
  .item {
    padding: 20px 0 20px 144px;
    border-bottom: 1px dashed #47BDF4;
    font-size: 14px;
    width: 100%;
    .item-group {
      .label {
        min-width: 99px;
        text-align: right;
        color: #999;
        vertical-align: top;
      }
      .label-h {
        line-height: 30px;
        height: 30px;
      }
      .box {
        display: inline-block;
        position: relative;
        .good-number {
          width: 200px;
          min-height: 30px;
          padding: 0 10px;
          line-height: 1.42857143;
          background-color: #fafafa;
          border: 1px solid #ececec;
          border-radius: 4px;
        }
      }
      .box-w {
        min-width: 500px;
      }
      .item-c {
        color: #666;
      }
      .tip {
        margin-top: 5px;
      }
    }
    .label-c {
      color: #999;
    }
    .label-b {
      color: #f00384;
      cursor: pointer;
    }
  }
  .large-input {
    .form-control {
      width: 200px;
    }
  }
  .goods-price {
    padding-bottom: 20px;

    .w-input {
      width: 80px;
      display: inline-block;
    }
  }
}
</style>